package com.zrrd.linestructure;

public class IntegerLinkedList {
    static class Node {
        Integer data;  //数据域
        Node next;  //后继指针域
        public Node(Integer data){
            this.data = data;
        }
        public Node(){
            this.data = data;
        }

    }
    private Node first;
    private int size;
    public void add(int num) {
        Node node = new Node();
        node.data = num;
        if (size == 0) {
            first = node;
            size++;
            return;
        }
        Node last = first;
        while (last.next != null) {
            last = last.next;
        }
        last.next = node;
        size++;
    }
    public int get(int index) {
        if (index < 0 || index > size - 1) {
            throw new IllegalArgumentException("链表下标越界：" + index);
        }
        int step = 0;
        Node cur = first;
        while (step < index) {
            cur = cur.next;
            step++;
        }
        return cur.data;
    }

    public int remove(int index) {
        if (index < 0 || index > size - 1) {
            throw new IllegalArgumentException("链表下表越界" + index);
        }
        if (index == 0) {
            int result = first.data;
            first = first.next;
            return result;
        }
        int step = 0;
        Node cur = first;
        while (step < index - 1) {
            cur = cur.next;
            step++;
        }
        Node removedPre = cur;
        Node removed = cur.next;
        Node removedNext = cur.next.next;
        removedPre.next = removedNext;
        size--;
        return removed.data;
    }
    public void insert(int index, int num) {
        if (index < 0 || index > size - 1) {
            throw new IllegalArgumentException("链表下表越界" + index);
        }
        Node node = new Node();
        node.data = num;
        if (index == 0) {
            Node cur = first;
            first = node;
            node.next = cur;
            size++;
            return;
        }
        int step = 0;
        Node cur = first;
        while (step < index - 1) {
            cur = cur.next;
            step++;
        }
        Node next = cur.next;
        cur.next = node;
        node.next = next;
        size++;
    }
    public int size() {
        return size;
    }
    public static void main(String[] args) {
        Node node = new Node(1);
        IntegerLinkedList list = new IntegerLinkedList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.remove(1);
        for (int i = 0; i < list.size; i++) {
            System.out.print(list.get(i));
        }
    }
}
